<?php

$server = new Swoole\Websocket\Server('0.0.0.0', 9502);

$server->on('start', function ($server) {
    $content = "swoole is started\n";
    writeLog($content, 'start');
});

$server->on('open', function ($server, $request) {

    $getArr = $request->get;
    $uid = $getArr['uid'];

    $fd = $request->fd;
    $server->bind($fd, $uid);
    $clientInfo = $server->getClientInfo($fd);

    $content = "fd为：" . $fd . "\nuid为：" . $clientInfo['uid'];
    writeLog($content, 'open');

});

$server->on('message', function ($server, $frame) {
    $content = "收到信息: {$frame->data}\n";
    writeLog($content, 'message');

    // 记录聊天内容
    $dataObj = \app\index\controller\MemberGroupsChat::add($frame->data);
    $ndataObj = json_decode($frame->data);
    foreach ($server->connections as $fd) {
        $clientInfo = $server->getClientInfo($fd);

        $dataObj->meFlag = $clientInfo['uid'] == $ndataObj->fromUserId ? true : false;
        $content = "发送信息: " . json_encode($dataObj) . "\n";
        writeLog($content, 'message');
        $server->push($fd, $dataObj);
    }
});

$server->on('close', function ($server, $fd) {
    $content = "connection close: {$fd}\n";
    writeLog($content, 'close');
});

$server->start();

function writeLog($content, $title = '')
{
    \app\common\controller\Log::insertLog($content, $title, 'swoole.log');
}
